package com.me.study.simpleMapperScan;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.beans.factory.FactoryBean;

/**
 * Mybatis-MapperScan 的 基本原理：根据接口类型生成实现类，并纳入 spring 管理
 *
 * @author ME
 * @date   2019/12/30
 */
public class DaoFactoryBean implements FactoryBean<Object>, InvocationHandler {
	private Class<?> clazz;

	/**
	 * 何时调用当前构造函数？见 MyImportBeanDefinitionRegistrar.java:34
	 */
	public DaoFactoryBean(Class<?> clazz) {
		this.clazz = clazz;
	}

	@Override
	public Object getObject() throws Exception {
		Object o = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[]{clazz}, this);
		return o;
	}

	@Override
	public Class<?> getObjectType() {
		return clazz;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		String[] querySql = method.getDeclaredAnnotation(Select.class).value();
		System.out.println("Mybatis-MapperScan 基本原理 Execute SQL: " + querySql[0]);
		return null;
	}
}
